//
// sdk.go
// Copyright (C) 2018 asxalex <asxalex@promote.cache-dns.local>
//
// Distributed under terms of the MIT license.
//

package filtersdk

import (
	"log"
	"time"

	"github.com/nats-io/go-nats"
)

const (
	// defaultNatsServer the default nats server
	defaultNatsServer = "nats://127.0.0.1:4222"
	basicPrefix       = "server.filters."
)

/*
Filter is the filter
*/
type Filter struct {
	URL     string
	Methods map[string]func([]byte)
}

/*
NewFilter creates a new filter
*/
func NewFilter() *Filter {
	f := &Filter{
		Methods: make(map[string]func([]byte)),
		URL:     "",
	}
	return f
}

/*
SetURL set the url of local service discovery
*/
func (f *Filter) SetURL(url string) {
	f.URL = url
}

/*
AddFilter adds the subject and its' handler accordingly.
*/
func (f *Filter) AddFilter(subject string, handler func([]byte)) {
	f.Methods[subject] = handler
}

func loopForever() {
	for {
		time.Sleep(10 * time.Second)
	}
}

/*
Run runs the filter
*/
func (f *Filter) Run() {
	if f.URL == "" {
		f.URL = defaultNatsServer
	}
	local, err := nats.Connect(f.URL)
	if err != nil {
		log.Fatalf("connects %s error: %s", f.URL, err.Error())
	}
	for subject, handler := range f.Methods {
		_, err := local.Subscribe(basicPrefix+subject, func(msg *nats.Msg) {
			handler(msg.Data)
		})
		if subject == "" {
			log.Printf("subject is empty, skip")
			continue
		}
		if err != nil {
			log.Fatalf("failed to scribe to %s, error:%s\n", subject, err.Error())
		}
	}
	loopForever()
}
